package jjn.round1;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Jiang Jining
 * @since 2023-06-10 16:05
 */
public class LeetCode216_CombinationV3 {
    public List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> result = new ArrayList<>();
        backtrack(k, n, 1, result, new ArrayList<>(), 0);
        return result;
    }
    
    private void backtrack(int k, int n, int startIndex, List<List<Integer>> result, List<Integer> path, int currentSum) {
        if (path.size() > k || currentSum > n) {
            return;
        }
        if (path.size() == k) {
            if (currentSum == n) {
                result.add(new ArrayList<>(path));
            }
            return;
        }
        for (int i = startIndex; i < 10; i++) {
            path.add(i);
            backtrack(k, n, i + 1, result, path, currentSum + i);
            path.remove(path.size() - 1);
        }
    }
}
